//
//  YDVerticalStockTimeLineView.m
//  PeiZiWangBei
//
//  Created by LK-IOS on 2018/1/7.
//  Copyright © 2018年 LK-IOS. All rights reserved.
//

#import "YDVerticalStockTimeLineView.h"
#import "StockTimeLineView.h"
#import "StockTimeVolumeView.h"
#import "UIView+StockViewExtension.h"
#import "UIColor+StockColorEntension.h"
#import "StockConst.h"
#import "StockTimeLineModel.h"
#import "StockLinePointModel.h"
#import "StockTimeVolumePositionModel.h"




@interface YDVerticalStockTimeLineView()<StockTimeLineViewDelegate>

/**
 当前绘制在屏幕上的数据源数组
 */
@property (nonatomic, strong) NSArray <__kindof StockTimeLineModel*>*timeLineModels;

@property (nonatomic , strong) StockTimeLineView *stockTimeLineView;

@property (nonatomic , strong) StockTimeVolumeView *stockTimeVolumeView;

/**
 长按手势
 */
@property (nonatomic,strong) UILongPressGestureRecognizer *longPress;

/**
 手势移动时的纵轴和横轴及中间圆圈
 */
@property (nonatomic,strong) CAShapeLayer *xLayer;
@property (nonatomic,strong) CAShapeLayer *yLayer;
@property (nonatomic,strong) CAShapeLayer *centerLayer;

/**
 显示时间的label
 */
@property (nonatomic,strong) UILabel *timeLabel;
@property (nonatomic , strong) UILabel *priceLabel;

/**
 当前选择的模型索引
 */
@property (nonatomic,assign) NSInteger curentModelIndex;

@end

@implementation YDVerticalStockTimeLineView


-(instancetype)initWithTimeLineModels:(NSArray<__kindof StockTimeLineModel *> *)timeLineModels
{
    self = [super init];
    if (self) {
        _timeLineModels = timeLineModels;
        
        [self stockTimeLineView];
        
        [self stockTimeVolumeView];
        
    }
    return self;
}


-(void)reDrawWithTimeLineModels:(NSArray<__kindof StockTimeLineModel *> *)timeLineModels
{
    _timeLineModels = timeLineModels;
    
    [_stockTimeLineView reDrawWithTimeLineModels:self.timeLineModels];
    
    [_stockTimeVolumeView reDrawWithTimeLineModels:self.timeLineModels];
    
    //开启异步线程添加手势，这样保证分时图的数据处理完成
//    dispatch_async(dispatch_get_main_queue(), ^{
//        if (self.timeLineModels.count) {
//
//            self.longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LongPressGesture:)];
//            [self addGestureRecognizer:self.longPress];
//
//            [self addGesturePressLayer];
//            [self addLabels];
//
//
//        }
//    });
}

-(void)drawGesturePressLine
{
    if (self.timeLineModels.count) {
        
        self.longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(LongPressGesture:)];
        [self addGestureRecognizer:self.longPress];
        
        [self addGesturePressLayer];
        [self addLabels];
    }
}

-(StockTimeLineView *)stockTimeLineView
{
    if (!_stockTimeLineView) {
        _stockTimeLineView = [[StockTimeLineView alloc] initWithTimeLineModels:self.timeLineModels];
        [self addSubview:_stockTimeLineView];
        _stockTimeLineView.delegate = self;
        [_stockTimeLineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(self);
            make.height.equalTo(self).multipliedBy(TimeLineViewHeightRate);
        }];
    }
    return _stockTimeLineView;
}

//左右间距和分时图的保持一致
-(StockTimeVolumeView *)stockTimeVolumeView
{
    if (!_stockTimeVolumeView) {
        _stockTimeVolumeView = [[StockTimeVolumeView alloc] initWithTimeLineModels:self.timeLineModels];
        [self addSubview:_stockTimeVolumeView];
        [_stockTimeVolumeView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.equalTo(self);
            make.top.equalTo(_stockTimeLineView.mas_bottom);
            make.height.equalTo(self).multipliedBy(1 - TimeLineViewHeightRate);
        }];
    }
    return _stockTimeVolumeView;
}

/**
 添加手指移动时的图层
 */
-(void)addGesturePressLayer
{
    //手势移动时，显示的横线
    self.xLayer = [CAShapeLayer layer];
    self.xLayer.lineWidth = TimeLineLineWidth;
    self.xLayer.lineCap = kCALineCapRound;
    self.xLayer.lineJoin = kCALineJoinRound;
    self.xLayer.strokeColor = [UIColor Stock_GesTureLineColor].CGColor;
    self.xLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.xLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:2],nil]];
    [self.layer addSublayer:self.xLayer];
    
    //手势移动时，显示的纵线
    self.yLayer = [CAShapeLayer layer];
    self.yLayer.lineWidth = TimeLineLineWidth;
    self.yLayer.lineCap = kCALineCapRound;
    self.yLayer.lineJoin = kCALineJoinRound;
    self.yLayer.strokeColor = [UIColor Stock_GesTureLineColor].CGColor;
    self.yLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.yLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:2],[NSNumber numberWithInt:2],nil]];
    [self.layer addSublayer:self.yLayer];
    
    
    //手势移动时随手势中信点移动的圆圈
    self.centerLayer = [CAShapeLayer layer];
    StockLinePointModel *nextPoint = [_stockTimeLineView.modelPostionArray lastObject];
    UIBezierPath *centerPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(nextPoint.xPosition, nextPoint.yPosition) radius:cycleRate startAngle:0 endAngle:2*M_PI clockwise:YES];
    self.centerLayer.path = centerPath.CGPath;
    self.centerLayer.lineWidth = TimeLineLineWidth;
    self.centerLayer.lineCap = kCALineCapRound;
    self.centerLayer.lineJoin = kCALineJoinRound;
    self.centerLayer.strokeColor = [UIColor Stcok_TimeCycleFillColor].CGColor;
    self.centerLayer.fillColor = [[UIColor clearColor] CGColor];
    [self.layer addSublayer:self.centerLayer];
    
    
    //开始绘图完成之后，默认显示的两条线
    CGPoint point = [_stockTimeLineView getLastModelPostion];

    UIBezierPath *xPath = [UIBezierPath bezierPath];
    [xPath moveToPoint:CGPointMake(point.x,0)];
    [xPath addLineToPoint:CGPointMake(point.x,self.height)];
    self.xLayer.path = xPath.CGPath;

    UIBezierPath *yPath = [UIBezierPath bezierPath];
    [yPath moveToPoint:CGPointMake(TimeLineLeftMargin,point.y)];
    [yPath addLineToPoint:CGPointMake(self.width - TimeLineRightMargin,point.y)];
    self.yLayer.path = yPath.CGPath;
}

/**
 创建手势移动时显示时间和涨跌幅度的label
 */
- (void)addLabels
{
    //时间
    _timeLabel = [self createLabel];
    [self addSubview:_timeLabel];
    _timeLabel.bounds = CGRectMake(0, 0, 0, 0);
    //价格或成交量
    _priceLabel = [self createLabel];
    [self addSubview:_priceLabel];
    _priceLabel.bounds = CGRectMake(0, 0, 0, 0);
}
/**
 长按手势代理
 */
- (void)LongPressGesture:(UILongPressGestureRecognizer*)longPress
{
    static CGFloat oldPositionX = 0;
    if(UIGestureRecognizerStateChanged == longPress.state || UIGestureRecognizerStateBegan == longPress.state)
    {
        if (self.delegate && [self.delegate respondsToSelector:@selector(verticalStockTimeLineViewGestureState:)]) {
            [self.delegate verticalStockTimeLineViewGestureState:GestureStateActivity];
        }
        
        CGPoint location = [longPress locationInView:self];
        CGFloat locationY = location.y;
        if (locationY <= _stockTimeLineView.height) {//在分时图上
            
            CGPoint point = [_stockTimeLineView getLongPressModelPostionWithXPostion:location.x];
            UIBezierPath *xPath = [UIBezierPath bezierPath];
            [xPath moveToPoint:CGPointMake(point.x,0)];
            [xPath addLineToPoint:CGPointMake(point.x,self.height)];
            self.xLayer.path = xPath.CGPath;
            
            UIBezierPath *yPath = [UIBezierPath bezierPath];
            [yPath moveToPoint:CGPointMake(TimeLineLeftMargin,point.y)];
            [yPath addLineToPoint:CGPointMake(self.width - TimeLineRightMargin,point.y)];
            self.yLayer.path = yPath.CGPath;
            
            
            UIBezierPath *centerPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(point.x, point.y) radius:cycleRate startAngle:0 endAngle:2*M_PI clockwise:YES];
            self.centerLayer.path = centerPath.CGPath;
            
            //手势在分时图上时只显示价格和时间
            StockTimeLineModel *model = [_stockTimeLineView getLongPressModel];
            //显示的价格字段
            NSString *priceString = [NSString stringWithFormat:@"%.2f" , [model.lastPirce floatValue]];
            NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
            CGRect timeLabelRect = [self rectOfNSString:model.currentTime attribute:attribute];
            CGRect priceLabelRect = [self rectOfNSString:[NSString stringWithFormat:@"%@" , priceString] attribute:attribute];
            
            //时间
            _timeLabel.frame = CGRectMake(0, 0, timeLabelRect.size.width, TimeLineTimeHeight);
            _timeLabel.center = CGPointMake(point.x, _stockTimeLineView.height - TimeLineTimeHeight + _timeLabel.height * 0.5);
            //价格
            _priceLabel.frame = CGRectMake(0, 0, priceLabelRect.size.width, TimeLineTimeHeight);
            _priceLabel.center = CGPointMake(TimeLineLeftMargin + priceLabelRect.size.width * 0.5, point.y);
            
            
            if (_timeLabel.center.x  + _timeLabel.width/2 >= self.width - TimeLineRightMargin)
            {
                _timeLabel.center = CGPointMake(self.width-_timeLabel.width/2 - TimeLineRightMargin, _stockTimeLineView.height - TimeLineTimeHeight + _timeLabel.height * 0.5);
            }
            
            else if (_timeLabel.center.x  - _timeLabel.width/2 <= TimeLineLeftMargin)
            {
                _timeLabel.center = CGPointMake(TimeLineLeftMargin + _timeLabel.width/2, _stockTimeLineView.height - TimeLineTimeHeight + _timeLabel.height * 0.5);
            }
            
            if ([model.priceChange floatValue] >= 0) {
                _priceLabel.textColor = [UIColor Stock_PriceUpColor];
            }else{
                _priceLabel.textColor = [UIColor Stock_PriceDownColor];
            }
            
            _timeLabel.text = [NSString stringWithFormat:@"%@",model.currentTime];
            _priceLabel.text = [NSString stringWithFormat:@"%@",priceString];
            _timeLabel.hidden = NO;
            _priceLabel.hidden = NO;
            oldPositionX = location.x;
            
        }else{//在成交量图上
            CGPoint Volumepoint = [_stockTimeVolumeView getLongPressModelPostionWithXPostion:location.x];
            
            CGPoint point = [_stockTimeVolumeView convertPoint:Volumepoint toView:self];
            
            UIBezierPath *xPath = [UIBezierPath bezierPath];
            [xPath moveToPoint:CGPointMake(point.x,0)];
            [xPath addLineToPoint:CGPointMake(point.x,self.height)];
            self.xLayer.path = xPath.CGPath;
            
            UIBezierPath *yPath = [UIBezierPath bezierPath];
            [yPath moveToPoint:CGPointMake(TimeLineLeftMargin,point.y)];
            [yPath addLineToPoint:CGPointMake(self.width - TimeLineRightMargin,point.y)];
            self.yLayer.path = yPath.CGPath;
            
            
            UIBezierPath *centerPath = [UIBezierPath bezierPathWithArcCenter:CGPointMake(point.x, point.y) radius:cycleRate startAngle:0 endAngle:2*M_PI clockwise:YES];
            self.centerLayer.path = centerPath.CGPath;
            
            //手势在分时图上时只显示价格和时间
            StockTimeLineModel *model = [_stockTimeVolumeView getLongPressModel];
            NSDictionary *attribute = @{NSFontAttributeName:[UIFont systemFontOfSize:12]};
            CGRect timeLabelRect = [self rectOfNSString:model.currentTime attribute:attribute];
            
            //成交量字符串
            NSString *volumeString = [self resloveVolume:model];
            CGRect priceLabelRect = [self rectOfNSString:volumeString attribute:attribute];
            
            //时间
            _timeLabel.frame = CGRectMake(0, 0, timeLabelRect.size.width, TimeLineTimeHeight);
            _timeLabel.center = CGPointMake(point.x, _stockTimeLineView.height - TimeLineTimeHeight + _timeLabel.height * 0.5);
            //成交量
            _priceLabel.frame = CGRectMake(0, 0, priceLabelRect.size.width, TimeLineTimeHeight);
            _priceLabel.center = CGPointMake(TimeLineLeftMargin + priceLabelRect.size.width * 0.5, point.y);
            
            
            if (_timeLabel.center.x  + _timeLabel.width/2 >= self.width - TimeLineRightMargin)
            {
                _timeLabel.center = CGPointMake(self.width-_timeLabel.width/2 - TimeLineRightMargin, _stockTimeLineView.height - TimeLineTimeHeight + _timeLabel.height * 0.5);
            }
            
            else if (_timeLabel.center.x  - _timeLabel.width/2 <= TimeLineLeftMargin)
            {
                _timeLabel.center = CGPointMake(TimeLineLeftMargin + _timeLabel.width/2, _stockTimeLineView.height - TimeLineTimeHeight + _timeLabel.height * 0.5);
            }
            
            
            if (_priceLabel.centerY - _priceLabel.height * 0.5 <= _stockTimeVolumeView.y) {
                _priceLabel.center = CGPointMake(_priceLabel.width * 0.5 + TimeLineLeftMargin, _stockTimeVolumeView.y + _priceLabel.height * 0.5);
            }else if (_priceLabel.centerY + _priceLabel.height * 0.5 >= _stockTimeVolumeView.y + _stockTimeVolumeView.height){
                _priceLabel.center = CGPointMake(_priceLabel.width * 0.5 + TimeLineLeftMargin, _stockTimeVolumeView.y +_stockTimeVolumeView.height -  _priceLabel.height * 0.5);
            }
            
            if ([model.priceChange floatValue] >= 0) {
                _priceLabel.textColor = [UIColor Stock_PriceUpColor];
            }else{
                _priceLabel.textColor = [UIColor Stock_PriceDownColor];
            }
            
            _timeLabel.text = [NSString stringWithFormat:@"%@",model.currentTime];
            _priceLabel.text = volumeString;
            _timeLabel.hidden = NO;
            _priceLabel.hidden = NO;
            oldPositionX = location.x;
            
            
        }
        
    }
    
    if(longPress.state == UIGestureRecognizerStateEnded)
    {
        self.xLayer.path = [UIBezierPath bezierPath].CGPath;
        self.yLayer.path = [UIBezierPath bezierPath].CGPath;
        self.centerLayer.path = [UIBezierPath bezierPath].CGPath;
        _timeLabel.hidden = YES;
        _priceLabel.hidden = YES;
        oldPositionX = 0;
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(verticalStockTimeLineViewGestureState:)]) {
            [self.delegate verticalStockTimeLineViewGestureState:GestureStateEnd];
        }
    }
}




-(UILabel*)createLabel
{
    UILabel *label = [UILabel new];
    label.textColor = [UIColor Stock_TextColor];
    label.adjustsFontSizeToFitWidth = YES;
    label.textAlignment = NSTextAlignmentCenter;
    label.backgroundColor = [UIColor Stock_GesTureLabelBackColor];
    label.hidden = YES;
    return label;
}

/**
 计算一个字段的宽高
 */
- (CGRect)rectOfNSString:(NSString *)string attribute:(NSDictionary *)attribute
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT, 0)
                                       options:NSStringDrawingTruncatesLastVisibleLine |NSStringDrawingUsesLineFragmentOrigin |
                   NSStringDrawingUsesFontLeading
                                    attributes:attribute
                                       context:nil];
    return rect;
}


//成交量处理
-(NSString *)resloveVolume:(StockTimeLineModel *)model
{
    CGFloat volume = [model.currentVolume floatValue];
    //尝试转为万手
    CGFloat wVolume = volume/10000.f;
    NSString *text, *descText;
    if (wVolume > 1) {
        //尝试转为亿手
        CGFloat yVolume = wVolume/10000.f;
        if (yVolume > 1) {
            text = [NSString stringWithFormat:@"%.2f",yVolume];
            descText = @"亿手";
        } else {
            text = [NSString stringWithFormat:@"%.2f",wVolume];
            descText = @"万手";
        }
    } else {
        text = [NSString stringWithFormat:@"%.0f",volume];
        descText = @"手";
    }
    
    NSString *labelText = [NSString stringWithFormat:@"%@%@" , text , descText];
    
    return labelText;
}

@end
